# -*- coding: utf-8 -*-
# FileName:     video_gui.py
# time:         22/12/9 009 下午 9:24
# Author:       Zhou Hang
# Description:  I don't want to write
import os
from enum import Enum
from pathlib import Path

from PySide6.QtCore import QUrl, Qt
from PySide6.QtGui import QIcon
from PySide6.QtMultimedia import QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget


class SizeState(Enum):
    FULL_SCREEN = 0
    NORMAL_SCREEN = 1


class MediaStatus:
    pass


class ZVideoWidget(QVideoWidget):
    def __init__(self, url=''):
        super(ZVideoWidget, self).__init__()
        self.cur_duration = None
        self.len_ppt = None
        self.min_ppt_number = None
        self.current_ppt = None
        self.max_ppt_number = None
        self.project_root = None
        self.is_stop = False
        self.size_state = SizeState.NORMAL_SCREEN
        self.normal_size = [0, 0, 800, 450]
        self.setGeometry(*self.normal_size)
        self.setWindowTitle("放映机")
        self.setWindowIcon(QIcon("../resource/icon/movie-ticket.png"))
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.player = QMediaPlayer()
        self.player.setSource(QUrl(url))
        self.player.setVideoOutput(self)
        # print(self.player.mediaStatus(), type(self.player.mediaStatus()))
        # 很多signal pyqt并不提示，这就很坑了
        self.player.mediaStatusChanged.connect(self.mediaStatus_change)
        self.player.positionChanged.connect(self.pause_at_last_frame)
        # self.playlist = QMediaPlaylist()  # 这东西在Pyside6中被移除了，nnd

    # TODO:有时候一个简单的功能需要多方面同时操作才能搞定！
    # 这里我只是想要一个视频播放完停止在最后一帧的效果而已！
    def pause_at_last_frame(self, position):
        if position > self.cur_duration - 100:
            # 这里position是会随机向上增长的，并不是线性顺序增长，所以只能给一个范围，大致到最后一帧了就停止
            self.pause()

    def mediaStatus_change(self, status):
        # print(status.value, status)
        if status.value == 5:  # 视频缓存
            self.cur_duration = self.player.duration()
        elif status.value == 5:  # 视频结束
            # 这里是一个备用措施，视频万一播放结束同样也可以停在最后一帧，不过这里会闪烁一下
            self.pause()
            self.player.setPosition(self.player.duration() - 20)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Escape:
            self.stop()
            if self.size_state == SizeState.FULL_SCREEN:
                self.size_state = SizeState.NORMAL_SCREEN
                self.showNormal()
            self.hide()
        elif key == Qt.Key_Return:
            if self.size_state == SizeState.NORMAL_SCREEN:
                self.size_state = SizeState.FULL_SCREEN
                self.showFullScreen()
            else:
                self.size_state = SizeState.NORMAL_SCREEN
                self.showNormal()
        elif key == Qt.Key_Space:
            if self.is_stop:
                self.play()
            else:
                self.pause()
        elif key in [Qt.Key_J, Qt.Key_Down, Qt.Key_S, Qt.Key_Left, Qt.Key_D, Qt.Key_L]:
            self.set_source(self.get_next_ppt())
            self.play()
            print("向下翻页")
        elif key in [Qt.Key_K, Qt.Key_Up, Qt.Key_W, Qt.Key_Right, Qt.Key_A, Qt.Key_H]:
            self.set_source(self.get_prev_ppt())
            self.play()
            print("向前翻页")
    
    def set_ppt_dir(self, dir_path):
        self.project_root = Path(dir_path)
        raw_data = []
        ppts = []
        for file in self.project_root.glob("*.mp4"):
            try:
                raw_data.append(file)
                ppts.append(int(file.stem))
            except ValueError:  # 出现不是数字编码的文件名就跳过
                continue
        ppts.sort()
        # self.playlist
        self.min_ppt_number = ppts[0]
        self.max_ppt_number = ppts[-1]
        self.len_ppt = len(ppts)
        self.current_ppt = self.min_ppt_number
        self.set_source(self.get_cur_ppt())
        return ppts

    def set_source(self, new_url):
        # print(new_url)
        self.player.setSource(QUrl(fr"{new_url}"))

    def play(self):
        self.is_stop = False
        self.player.play()

    def stop(self):
        self.is_stop = True
        self.player.stop()

    def pause(self):
        self.is_stop = True
        self.player.pause()

    def get_cur_ppt(self):
        ret = str(self.project_root / f'{self.current_ppt}.mp4')
        ret = ret.replace('\\', '/')
        return ret

    def get_next_ppt(self):
        self.current_ppt += 1
        if self.current_ppt > self.max_ppt_number:
            self.current_ppt = self.min_ppt_number
        # self.current_ppt = self.min_ppt_number + (self.current_ppt + 1 % (self.len_ppt + 1))
        return self.get_cur_ppt()

    def get_prev_ppt(self):
        self.current_ppt -= 1
        if self.current_ppt < self.min_ppt_number:
            self.current_ppt = self.max_ppt_number
        return self.get_cur_ppt()

    def set_cur_ppt(self, new_num):
        if not isinstance(new_num, int):
            new_num = int(new_num)
        self.current_ppt = new_num
        self.set_source(self.get_cur_ppt())


def main():
    pass


if __name__ == "__main__":
    main()
